import { effects } from 'dva-core/saga';
import { message as antMessage, Button } from 'antd';
import axios from 'axios';
import { throttle } from '@/utils/common';

export const HTTP_STATUS = {
  SUCCESS: 200,
  PARAMERROR: 400,
};
export const API_STATUS = {
  SUCCESS: 1,
  AUTHENTICATE: 1007,
  ACCOUNT_NOT_EXIST: 2005,
};

export function* request(payload) {
  const { url, data, method, isList, type } = payload;
  const token = sessionStorage.getItem('token');
  let res;
  try {
    if (method === 'get') {
      res = yield axios.get(url, {
        headers: { token },
        params: data,
      });
    } else {
      res = yield axios.post(url, data, {
        headers: { token },
      });
    }
  } catch (e) {
    yield effects.put({
      type: '$msg/showToast',
      payload: { title: '系统异常，请稍后再试' },
    });
    return Promise.reject(e);
  }

  if (!res.data) return;
  const { code, message } = res.data;

  if (code === API_STATUS.SUCCESS) {
    return Promise.resolve(res.data.data);
  } else if (
    code === API_STATUS.AUTHENTICATE ||
    code === API_STATUS.ACCOUNT_NOT_EXIST
  ) {
    // yield effects.put({ type: '$error/auth', payload: res.data });
    throttle(() => {
      const mst =
        code === API_STATUS.AUTHENTICATE ? '登录信息失效，请重新登录' : message;
      antMessage.error(mst);
    }, 2000);
    yield effects.put({
      type: '$router/forward',
      payload: {
        url: 'login',
      },
    });
  } else {
    yield effects.put({
      type: '$msg/showToast',
      payload: {
        title: res.data.message,
      },
    });
  }
  return Promise.reject(res.data);
}

export default {
  namespace: '$request',
  state: {},
  effects: {
    *get({ payload }) {
      return yield request({ ...payload, method: 'get' });
    },
    *post({ payload }) {
      return yield request({ ...payload, method: 'post' });
    },
  },
};
